package com.heima.wemedia.service.impl;


import com.heima.apis.article.IArticleClient;
import com.heima.model.comment.dtos.CommentArticleDto;
import com.heima.model.comment.dtos.CommentListDto;
import com.heima.model.comment.dtos.CommentOperationDto;
import com.heima.model.comment.dtos.WmCommentRepayDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.pojos.*;
import com.heima.wemedia.service.CommentManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @projectName: heima-leadnews0802
 * @package: com.heima.admin.service.impl
 * @className: AdCommentManageServiceImpl
 * @author: AoQing
 * @date: 2023/8/2 9:42
 * @version: 1.0
 */

@Service
@Slf4j
public class CommentManageServiceImpl implements CommentManageService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private IArticleClient articleClient;


    @Autowired
    private WmUserMapper wmUserMapper;
    /**
     * 查看评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(CommentListDto dto) {

        List<CommentPageListVo> commentPageListVos=new ArrayList<>();
        //校验参数
        if(dto == null || dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //按照时间倒叙查询发布的文章
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
      /*  Pageable pageable =  PageRequest.of(dto.getPage(),dto.getSize());
        query.with(pageable);
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));*/
        //查询符合条件的评论

        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);

        //遍历
        for (ApComment apComment : apComments) {
            CommentPageListVo commentPageListVo = new CommentPageListVo();
            commentPageListVo.setApComments(apComment);
            Query query1 = Query.query(Criteria.where("commentId").is(apComment.getId()));
            query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
            List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query1, ApCommentRepay.class);
            commentPageListVo.setApCommentRepays(apCommentRepays);
            commentPageListVos.add(commentPageListVo);
        }


        return ResponseResult.okResult(commentPageListVos);


    }

    @Override
    public ResponseResult openOrCloseComment(CommentOperationDto dto) {
      /*  //参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //打开评论，可以让任何用户评论该文章
        //关闭评论，不让任何用户评论该文章，关闭评论，则清除所有该文章的评论
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        if (apComments != null && apComments.size() > 0) {
            for (ApComment apComment : apComments) {
                //删除关联的评论点赞
                Query query1 = Query.query(Criteria.where("commentId").is(apComment.getId()));
                List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
                mongoTemplate.remove(apCommentLikes);
                //删除关联的评论回复
                Query query2 = Query.query(Criteria.where("commentId").is(apComment.getId()));
                List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query2, ApCommentRepay.class);
                mongoTemplate.remove(apCommentRepays);
            }
        }*/

        WmUser wmUser = WmThreadLocalUtil.getUser();

        //app端用户id
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        Integer apUserId = dbUser.getApUserId();

        //清空该文章的所有评论
        List<ApComment> apCommentList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("authorId").is(apUserId)), ApComment.class);
        for (ApComment apComment : apCommentList) {
            List<ApCommentRepay> commentRepayList = mongoTemplate.find(Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(apUserId)), ApCommentRepay.class);
            List<String> commentRepayIdList = commentRepayList.stream().map(ApCommentRepay::getId).distinct().collect(Collectors.toList());
            //删除所有的评论回复点赞数据
          //  mongoTemplate.remove(Query.query(Criteria.where("commentRepayId").in(commentRepayIdList).and("authorId").is(apUserId)), ApCommentRepayLike.class);

            //删除该评论的所有的回复内容
            mongoTemplate.remove(Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("authorId").is(apUserId)), ApCommentRepay.class);

            //删除评论的点赞
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(apUserId)), ApCommentLike.class);

        }
        //删除评论
        mongoTemplate.remove(Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("authorId").is(apUserId)),ApComment.class);

        //修改评论状态
        return articleClient.updateArticleStatus(dto);
    }


    /**
     * 文章评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findNewsComments(CommentArticleDto dto) {
        //查看当前用户的文章
        WmUser user = WmThreadLocalUtil.getUser();
        dto.setWmUserId(user.getId());
        log.info("{}",user.getId());
        return articleClient.findNewsComments(dto);
    }

    /**
     * 删除评论
     * @param commentId
     * @return
     */
    @Override
    public ResponseResult delComment(String commentId) {
        //校验参数
        if (StringUtils.isBlank(commentId)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //删除评论
        Query query = Query.query(Criteria.where("id").is(commentId));
        mongoTemplate.remove(query,ApComment.class);
        //删除与之关联的回复评论
        Query query1 = Query.query(Criteria.where("commentId").is(commentId));
        mongoTemplate.remove(query1,ApCommentRepay.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 作者点赞评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(ApCommentLikeDto dto) {
        //参数校验
        if (dto ==null || StringUtils.isEmpty(dto.getCommentId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmUser user = WmThreadLocalUtil.getUser();
        WmUser wmUser = wmUserMapper.selectById(user.getId());
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //更新评论
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        Integer likes=dto.getOperation().equals(0)?apComment.getLikes()+1:apComment.getLikes()-1;
        apComment.setLikes(likes);
        mongoTemplate.save(apComment);
        if (dto.getOperation().equals(0)){
            //进行点赞
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setAuthorId(apComment.getAuthorId());
            mongoTemplate.insert(apCommentLike);
        }else {
            //取消点赞
            ApCommentLike commentId = mongoTemplate.findOne(Query.query(Criteria
                    .where("commentId").is(dto.getCommentId())), ApCommentLike.class);
            mongoTemplate.remove(commentId);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除回复评论
     * @param commentRepayId
     * @return
     */
    @Override
    public ResponseResult delCommentReply(String commentRepayId) {
        //校验参数
        if(StringUtils.isBlank(commentRepayId)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //删除回复评论
      mongoTemplate.remove(Query.query(Criteria.where("id").is(commentRepayId)),ApCommentRepay.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 回复评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult commentRepay(WmCommentRepayDto dto) {
       //校验参数
       if (dto==null || dto.getCommentId()==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
       }
        WmUser user = WmThreadLocalUtil.getUser();
        WmUser wmUser = wmUserMapper.selectById(user.getId());
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setAuthorId(wmUser.getId());
        apCommentRepay.setAuthorName(wmUser.getName());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        mongoTemplate.save(apCommentRepay);
        //更新
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
